package com.maimao.kill.client.fallback;

import cn.hutool.core.util.StrUtil;
import com.maimao.core.enums.RespCode;
import com.maimao.core.model.resp.Result;
import com.maimao.kill.client.GoodsClient;
import com.maimao.kill.client.ShopClient;
import com.maimao.model.goods.GoodsSku;
import com.maimao.model.kill.input.ApplySkuNewInput;
import feign.hystrix.FallbackFactory;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/11/30 10:03 下午
 */
@Component
@Slf4j
public class GoodsCallBackFactory implements FallbackFactory<GoodsClient> {

    @Override
    public GoodsClient create(Throwable cause) {
        String errorMsg = cause.getMessage() == null ? "" : cause.getMessage();
        return new GoodsClient() {
            @Override
            public Result<ApplySkuNewInput> checkSkuIsNew(ApplySkuNewInput input) {
                log.error("调用[GoodsClient-checkSkuIsNew({})]出错 :{}", input, errorMsg);

                return Result.fail(RespCode.FAIL, errorMsg);
            }

            @Override
            public Result<Void> updateSkuBatch(List<GoodsSku> skus) {
                StringBuilder sb = new StringBuilder();
                sb.append("调用[GoodsClient-updateSkuBatch({})]出错 :{}\n");
                boolean globalTc = false;
                if (!StrUtil.isBlank(RootContext.getXID())) {
                    try {
                        GlobalTransactionContext.reload(RootContext.getXID()).rollback();
                        sb.append("执行回滚，xid:{}");
                        globalTc = true;
                    } catch (TransactionException e) {
                        e.printStackTrace();
                        log.error("回滚失败,降级方法:[GoodsClient-updateSkuBatch()],xid:{}", RootContext.getXID());
                    }
                }
                if (globalTc) {
                    log.error(sb.toString(), skus, errorMsg, RootContext.getXID());
                } else {
                    log.error(sb.toString(), skus, errorMsg);
                }

                return Result.fail(errorMsg);
            }

            @Override
            public Result<List<GoodsSku>> getSkuKillInfoBatch(List<Long> skuIds) {
                log.error("调用[GoodsClient-getSkuKillInfoBatch({})]出错 :{}", skuIds, errorMsg);

                return Result.fail(RespCode.FAIL, errorMsg);
            }
        };
    }
}
